package com.company.project.robot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.company.project.common.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author ZYF
 * @date 2021/10/6 10:43
 */
@Service
public class CityServiceImpl {


    @Autowired
    HttpUtils httpUtils;

    /**
     * 获取城市对应代码
     * @param cityNam
     * @return
     * @throws Exception
     */
    public String getCityCode(String cityNam) throws Exception {
        // 定义城市代码
        String cityCode = "";
        String strUrl = "http://toy1.weather.com.cn/search?cityname=" + URLEncoder.encode(cityNam, "utf-8");
        String response =   httpUtils.get(strUrl,null);
        cityCode = response.substring(10, 19);
        return cityCode;
    }

    public HashMap<String, String> getWeatherInfo(String cityName) throws Exception {
        // 定义天气信息哈希映射
        HashMap<String, String> weather = new HashMap<>();
        String cityCode = getCityCode(cityName);
        // 定义url字符串
        String strUrl = "http://wthrcdn.etouch.cn/weather_mini?citykey=" + cityCode;
        String response =  httpUtils.get(strUrl,null);
        JSONObject obj = JSONObject.parseObject(response).getJSONObject("data");
        JSONObject today = JSONObject.parseObject(obj.getJSONArray("forecast").get(0).toString());
        weather.put("city", obj.getString("city"));
        weather.put("date",today.getString("date"));
        weather.put("high", today.getString("high"));
        weather.put("low",today.getString("low"));
        weather.put("fengxiang",   today.getString("fengxiang"));
        weather.put("type",   today.getString("type"));
        JSONObject tomorrow = JSONObject.parseObject(obj.getJSONArray("forecast").get(1).toString());
        weather.put("high1", tomorrow.getString("high"));
        weather.put("low1",tomorrow.getString("low"));
        weather.put("fengxiang1",   tomorrow.getString("fengxiang"));
        weather.put("type1",   tomorrow.getString("type"));
        return weather;
    }
}
